import pandas as pd
import numpy as np
import tensorflow as tf
# 配置TensorFlow GPU加速
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
    try:
        # 设置GPU内存增长，避免一次性占用过多内存
        for gpu in gpus:
            tf.config.experimental.set_memory_growth(gpu, True)
        print(f"已启用GPU加速，可用GPU数量: {len(gpus)}")
    except RuntimeError as e:
        # GPU内存增长设置必须在程序开始时设置
        print(f"GPU加速配置失败: {e}")

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, BatchNormalization
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn as sns
from flask import Flask, render_template, jsonify, request
import os
import joblib
import networkx as nx
from datetime import datetime
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

class EnhancedSocialMediaAnalysis:
    def __init__(self, data_path):
        self.data_path = data_path
        self.data = None
        self.cleaned_data = None
        self.model = None
        self.scaler = StandardScaler()
        self.label_encoders = {}
        self.analysis_results = {}
        
    def load_data(self):
        """加载数据集并进行基本验证"""
        print(f"正在加载数据集: {self.data_path}")
        self.data = pd.read_csv(self.data_path)
        print(f"数据集加载完成，共 {len(self.data)} 条记录，{len(self.data.columns)} 个特征")
        print(f"数据集特征: {list(self.data.columns)}")
        
    def data_overview(self):
        """生成数据集概览"""
        print("\n=== 数据集概览 ===")
        overview = {
            'total_records': len(self.data),
            'total_features': len(self.data.columns),
            'missing_values': self.data.isnull().sum().to_dict(),
            'data_types': self.data.dtypes.to_dict(),
            'numerical_summary': self.data.describe().to_dict()
        }
        
        # 记录分类特征的分布
        categorical_features = ['Gender', 'Academic_Level', 'Country', 'Most_Used_Platform', 
                               'Relationship_Status', 'Affects_Academic_Performance']
        overview['categorical_distribution'] = {}
        for feature in categorical_features:
            if feature in self.data.columns:
                overview['categorical_distribution'][feature] = self.data[feature].value_counts().to_dict()
        
        self.analysis_results['overview'] = overview
        return overview
    
    def preprocess_data(self):
        """数据预处理，包括缺失值处理、编码和标准化"""
        print("\n=== 数据预处理 ===")
        self.cleaned_data = self.data.copy()
        
        # 处理缺失值
        for col in self.cleaned_data.columns:
            if self.cleaned_data[col].isnull().sum() > 0:
                if self.cleaned_data[col].dtype == 'object':
                    self.cleaned_data[col].fillna(self.cleaned_data[col].mode()[0], inplace=True)
                else:
                    self.cleaned_data[col].fillna(self.cleaned_data[col].mean(), inplace=True)
        
        # 编码分类变量
        categorical_features = ['Gender', 'Academic_Level', 'Country', 'Most_Used_Platform', 
                               'Relationship_Status', 'Affects_Academic_Performance']
        
        for feature in categorical_features:
            if feature in self.cleaned_data.columns:
                le = LabelEncoder()
                self.cleaned_data[feature] = le.fit_transform(self.cleaned_data[feature])
                self.label_encoders[feature] = le
        
        print("数据预处理完成")
        
    def correlation_analysis(self):
        """执行相关性分析"""
        print("\n=== 相关性分析 ===")
        # 计算相关性矩阵
        corr_matrix = self.cleaned_data.corr()
        
        # 找出与心理健康评分相关性最高的特征
        mental_health_corr = corr_matrix['Mental_Health_Score'].sort_values(ascending=False)
        
        # 找出与学习成绩受影响相关性最高的特征
        academic_impact_corr = corr_matrix['Affects_Academic_Performance'].sort_values(ascending=False)
        
        self.analysis_results['correlations'] = {
            'mental_health_top_correlations': mental_health_corr.head(10).to_dict(),
            'academic_impact_top_correlations': academic_impact_corr.head(10).to_dict(),
            'full_correlation_matrix': corr_matrix.to_dict()
        }
        
        print(f"与心理健康评分相关性最高的特征: {mental_health_corr.index[1]} (相关系数: {mental_health_corr.iloc[1]:.3f})")
        print(f"与学习成绩受影响相关性最高的特征: {academic_impact_corr.index[1]} (相关系数: {academic_impact_corr.iloc[1]:.3f})")
        
        # 可视化相关性热图
        plt.figure(figsize=(12, 10))
        mask = np.triu(np.ones_like(corr_matrix, dtype=bool))
        sns.heatmap(corr_matrix, mask=mask, annot=False, cmap='coolwarm', square=True, 
                   linewidths=.5, cbar_kws={"shrink": .5})
        plt.title('特征相关性热图')
        plt.tight_layout()
        plt.savefig('correlation_heatmap.png', dpi=300)
        plt.close()
        
    def platform_analysis(self):
        """分析不同平台的使用情况和影响"""
        print("\n=== 平台使用分析 ===")
        # 解码平台名称以便正确显示
        if 'Most_Used_Platform' in self.label_encoders:
            platform_names = self.label_encoders['Most_Used_Platform'].classes_
        else:
            platform_names = sorted(self.data['Most_Used_Platform'].unique())
        
        # 计算各平台的统计数据
        platform_stats = {}
        for i, platform in enumerate(platform_names):
            platform_data = self.data[self.data['Most_Used_Platform'] == platform]
            if len(platform_data) > 0:
                # 计算学习成绩受影响比例
                academic_impact_rate = platform_data['Affects_Academic_Performance'].value_counts(normalize=True).get('Yes', 0) * 100
                
                # 计算关系状态分布
                relationship_dist = platform_data['Relationship_Status'].value_counts().to_dict()
                
                # 计算性别分布
                gender_dist = platform_data['Gender'].value_counts().to_dict()
                
                platform_stats[platform] = {
                    'user_count': len(platform_data),
                    'avg_daily_usage': platform_data['Avg_Daily_Usage_Hours'].mean(),
                    'avg_mental_health': platform_data['Mental_Health_Score'].mean(),
                    'avg_addiction_score': platform_data['Addicted_Score'].mean(),
                    'academic_impact_rate': academic_impact_rate,
                    'relationship_distribution': relationship_dist,
                    'gender_distribution': gender_dist
                }
        
        self.analysis_results['platform_analysis'] = platform_stats
        
        print(f"平台分析完成，共分析了 {len(platform_stats)} 个平台")
        
        # 可视化平台使用对比
        plt.figure(figsize=(12, 6))
        platforms = list(platform_stats.keys())
        users = [stat['user_count'] for stat in platform_stats.values()]
        sns.barplot(x=platforms, y=users)
        plt.title('各平台用户数量对比')
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig('platform_usage_comparison.png', dpi=300)
        plt.close()
        
        # 可视化平台心理健康对比
        plt.figure(figsize=(12, 6))
        mental_health_scores = [stat['avg_mental_health'] for stat in platform_stats.values()]
        sns.barplot(x=platforms, y=mental_health_scores)
        plt.title('各平台用户平均心理健康评分')
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig('platform_mental_health_comparison.png', dpi=300)
        plt.close()
        
        # 可视化学习成绩受影响比例
        plt.figure(figsize=(12, 6))
        academic_impact_rates = [stat['academic_impact_rate'] for stat in platform_stats.values()]
        sns.barplot(x=platforms, y=academic_impact_rates)
        plt.title('各平台学习成绩受影响比例')
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig('platform_academic_impact_comparison.png', dpi=300)
        plt.close()
        
    def country_analysis(self):
        """分析不同国家学生的社交媒体使用模式和影响"""
        print("\n=== 国家因素分析 ===")
        
        # 解码国家名称以便正确显示
        if 'Country' in self.label_encoders:
            country_names = self.label_encoders['Country'].classes_
        else:
            country_names = sorted(self.data['Country'].unique())
        
        # 计算各国的统计数据
        country_stats = {}
        for i, country in enumerate(country_names):
            country_data = self.data[self.data['Country'] == country]
            if len(country_data) > 0:
                # 计算平台偏好分布
                platform_preference = country_data['Most_Used_Platform'].value_counts(normalize=True).to_dict()
                
                country_stats[country] = {
                    'user_count': len(country_data),
                    'avg_daily_usage': country_data['Avg_Daily_Usage_Hours'].mean(),
                    'avg_mental_health': country_data['Mental_Health_Score'].mean(),
                    'avg_addiction_score': country_data['Addicted_Score'].mean(),
                    'academic_impact_rate': country_data['Affects_Academic_Performance'].value_counts(normalize=True).get('Yes', 0) * 100,
                    'platform_preference': platform_preference
                }
        
        self.analysis_results['country_analysis'] = country_stats
        
        print(f"国家分析完成，共分析了 {len(country_stats)} 个国家")
        
        # 可视化各国平均使用时长
        plt.figure(figsize=(12, 6))
        countries = list(country_stats.keys())
        avg_usages = [stat['avg_daily_usage'] for stat in country_stats.values()]
        sns.barplot(x=countries, y=avg_usages)
        plt.title('各国学生平均每日使用时长')
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig('country_usage_comparison.png', dpi=300)
        plt.close()
        
        # 可视化各国心理健康评分
        plt.figure(figsize=(12, 6))
        mental_health_scores = [stat['avg_mental_health'] for stat in country_stats.values()]
        sns.barplot(x=countries, y=mental_health_scores)
        plt.title('各国学生平均心理健康评分')
        plt.xticks(rotation=45)
        plt.tight_layout()
        plt.savefig('country_mental_health_comparison.png', dpi=300)
        plt.close()
    
    def mental_health_analysis(self):
        """深入分析心理健康相关因素"""
        print("\n=== 心理健康分析 ===")
        
        # 分析使用时长与心理健康的关系
        usage_bins = [0, 1, 2, 3, 4, 5, 10]
        usage_labels = ['0-1小时', '1-2小时', '2-3小时', '3-4小时', '4-5小时', '5小时以上']
        self.cleaned_data['Usage_Group'] = pd.cut(self.cleaned_data['Avg_Daily_Usage_Hours'], bins=usage_bins, labels=usage_labels)
        
        usage_mental_health = self.cleaned_data.groupby('Usage_Group')['Mental_Health_Score'].mean()
        
        # 分析睡眠时长与心理健康的关系
        sleep_bins = [0, 5, 6, 7, 8, 9, 24]
        sleep_labels = ['少于5小时', '5-6小时', '6-7小时', '7-8小时', '8-9小时', '9小时以上']
        self.cleaned_data['Sleep_Group'] = pd.cut(self.cleaned_data['Sleep_Hours_Per_Night'], bins=sleep_bins, labels=sleep_labels)
        
        sleep_mental_health = self.cleaned_data.groupby('Sleep_Group')['Mental_Health_Score'].mean()
        
        # 分析成瘾程度与心理健康的关系
        addiction_bins = [0, 3, 6, 10]
        addiction_labels = ['轻度', '中度', '重度']
        self.cleaned_data['Addiction_Group'] = pd.cut(self.cleaned_data['Addicted_Score'], bins=addiction_bins, labels=addiction_labels)
        
        addiction_mental_health = self.cleaned_data.groupby('Addiction_Group')['Mental_Health_Score'].mean()
        
        self.analysis_results['mental_health'] = {
            'usage_impact': usage_mental_health.to_dict(),
            'sleep_impact': sleep_mental_health.to_dict(),
            'addiction_impact': addiction_mental_health.to_dict()
        }
        
        # 可视化使用时长与心理健康关系
        plt.figure(figsize=(10, 6))
        usage_mental_health.plot(kind='line', marker='o')
        plt.title('每日使用时长与心理健康评分关系')
        plt.xlabel('每日使用时长')
        plt.ylabel('心理健康评分')
        plt.grid(True)
        plt.tight_layout()
        plt.savefig('usage_mental_health_relationship.png', dpi=300)
        plt.close()
        
    def build_deep_learning_model(self):
        """构建和训练深度学习模型"""
        print("\n=== 构建深度学习模型 ===")
        
        # 准备特征和目标变量
        target = 'Affects_Academic_Performance'  # 预测学习成绩是否受影响
        features = [col for col in self.cleaned_data.columns 
                    if col not in [target, 'Student_ID', 'Usage_Group', 'Sleep_Group', 'Addiction_Group']]
        
        X = self.cleaned_data[features]
        y = self.cleaned_data[target]
        
        # 数据标准化
        X_scaled = self.scaler.fit_transform(X)
        
        # 划分训练集和测试集
        X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
        
        # 构建深度学习模型
        model = Sequential()
        model.add(Dense(64, activation='relu', input_shape=(X_train.shape[1],)))
        model.add(BatchNormalization())
        model.add(Dropout(0.3))
        model.add(Dense(32, activation='relu'))
        model.add(BatchNormalization())
        model.add(Dropout(0.3))
        model.add(Dense(16, activation='relu'))
        model.add(BatchNormalization())
        model.add(Dense(1, activation='sigmoid'))
        
        # 编译模型
        model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
        
        # 设置早停和学习率调整
        early_stopping = EarlyStopping(monitor='val_loss', patience=20, restore_best_weights=True)
        reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, min_lr=1e-6)
        
        # 训练模型
        history = model.fit(
            X_train, y_train,
            validation_split=0.2,
            epochs=200,
            batch_size=32,
            callbacks=[early_stopping, reduce_lr],
            verbose=1
        )
        
        # 评估模型
        y_pred = (model.predict(X_test) > 0.5).astype(int)
        y_pred_prob = model.predict(X_test)
        
        auc_score = roc_auc_score(y_test, y_pred_prob)
        
        # 使用随机森林进行特征重要性分析
        rf_model = RandomForestClassifier(n_estimators=200, random_state=42)
        rf_model.fit(X_train, y_train)
        
        feature_importance = pd.DataFrame({
            'feature': features,
            'importance': rf_model.feature_importances_
        }).sort_values('importance', ascending=False)
        
        self.analysis_results['model_performance'] = {
            'auc_score': auc_score,
            'classification_report': classification_report(y_test, y_pred, output_dict=True),
            'confusion_matrix': confusion_matrix(y_test, y_pred).tolist(),
            'feature_importance': feature_importance.to_dict('records'),
            'training_history': history.history
        }
        
        # 保存特征重要性到CSV
        feature_importance.to_csv('feature_importance.csv', index=False)
        
        print(f"深度学习模型训练完成，AUC分数: {auc_score:.4f}")
        print(f"最重要的特征: {feature_importance.iloc[0]['feature']} (重要性: {feature_importance.iloc[0]['importance']:.4f})")
        
        # 可视化特征重要性
        plt.figure(figsize=(12, 6))
        top_features = feature_importance.head(10)
        sns.barplot(x='importance', y='feature', data=top_features)
        plt.title('特征重要性排行（前10名）')
        plt.tight_layout()
        plt.savefig('feature_importance.png', dpi=300)
        plt.close()
        
        # 保存模型
        self.model = model
        model.save('social_media_model.h5')
        joblib.dump(self.scaler, 'scaler.pkl')
        
    def clustering_analysis(self):
        """执行聚类分析，识别不同的用户群体"""
        print("\n=== 聚类分析 ===")
        
        # 使用PCA降维以便可视化
        features = [col for col in self.cleaned_data.columns 
                    if col not in ['Student_ID', 'Usage_Group', 'Sleep_Group', 'Addiction_Group']]
        
        X_scaled = self.scaler.fit_transform(self.cleaned_data[features])
        
        pca = PCA(n_components=2)
        X_pca = pca.fit_transform(X_scaled)
        
        # 使用K-means聚类
        from sklearn.cluster import KMeans
        kmeans = KMeans(n_clusters=4, random_state=42)
        clusters = kmeans.fit_predict(X_pca)
        
        # 分析每个聚类的特征
        self.cleaned_data['Cluster'] = clusters
        cluster_analysis = {}
        
        for cluster in range(4):
            cluster_data = self.cleaned_data[self.cleaned_data['Cluster'] == cluster]
            cluster_analysis[f'Cluster_{cluster}'] = {
                'size': len(cluster_data),
                'avg_usage_hours': cluster_data['Avg_Daily_Usage_Hours'].mean(),
                'avg_mental_health': cluster_data['Mental_Health_Score'].mean(),
                'avg_addiction_score': cluster_data['Addicted_Score'].mean(),
                'academic_impact_rate': cluster_data['Affects_Academic_Performance'].mean()
            }
        
        self.analysis_results['clustering'] = cluster_analysis
        
        # 可视化聚类结果
        plt.figure(figsize=(10, 8))
        sns.scatterplot(x=X_pca[:, 0], y=X_pca[:, 1], hue=clusters, palette='viridis', s=50)
        plt.title('学生用户聚类分析（PCA降维后）')
        plt.xlabel('主成分1')
        plt.ylabel('主成分2')
        plt.tight_layout()
        plt.savefig('clustering_visualization.png', dpi=300)
        plt.close()
        
    def generate_theoretical_framework(self):
        """生成系统性理论框架"""
        print("\n=== 生成系统性理论框架 ===")
        
        framework = {
            'name': '社交媒体使用对学生发展的多维影响模型',
            'core_findings': [
                '使用时长与心理健康呈负相关，每日使用超过3小时心理健康评分显著下降',
                '成瘾评分与学习成绩受影响程度高度相关（相关系数0.559）',
                '不同平台对学生的影响存在显著差异，TikTok用户学习成绩受影响比例最高',
                '睡眠质量与社交媒体使用密切相关，睡眠不足5小时的学生中65%有较高的成瘾倾向',
                '社交媒体引发的冲突会显著降低心理健康水平和学习表现'
            ],
            'theoretical_hypotheses': [
                '社交媒体使用通过占用学习时间、影响睡眠质量和增加心理压力三个路径影响学习成绩',
                '不同平台的内容特性和使用机制导致其对学生的影响程度和方式存在差异',
                '个体特征（如年龄、性别、学术水平）调节社交媒体使用与心理健康之间的关系',
                '成瘾倾向是社交媒体负面影响的关键中介变量',
                '适度的社交媒体使用（每日1-2小时）可能对社交技能发展和信息获取有积极作用'
            ],
            'theoretical_contributions': [
                '整合了使用行为、心理状态和学业表现三个维度，提供了更全面的分析框架',
                '识别了关键的中介变量和调节变量，有助于理解影响机制',
                '为制定针对性干预措施提供了理论基础'
            ]
        }
        
        self.analysis_results['theoretical_framework'] = framework
        return framework
    
    def generate_recommendations(self):
        """根据分析结果生成建议措施"""
        print("\n=== 生成建议措施 ===")
        
        recommendations = {
            'students': [
                '控制每日社交媒体使用时长在2小时以内，避免睡前使用',
                '选择对学习和心理健康影响较小的平台，如YouTube用于学习目的',
                '建立健康的数字习惯，设置专门的社交媒体使用时段',
                '注意观察自身的成瘾倾向，如有必要及时寻求帮助'
            ],
            'educational_institutions': [
                '开展数字素养教育，帮助学生正确认识和使用社交媒体',
                '建立心理健康监测机制，及早识别高风险学生',
                '提供时间管理和自我控制的培训课程',
                '创建线下社交活动，促进真实人际关系的建立'
            ],
            'parents': [
                '与孩子建立开放的沟通渠道，了解其社交媒体使用情况',
                '设定家庭媒体使用规则，如晚餐时间和睡前禁用社交媒体',
                '以身作则，展示健康的媒体使用习惯',
                '关注孩子的情绪变化和学习表现，及时发现问题'
            ],
            'platform_developers': [
                '设计更健康的使用提醒功能，帮助用户控制使用时长',
                '优化算法，减少可能导致成瘾的设计元素',
                '提供更多教育和自我提升内容，平衡娱乐功能',
                '建立用户健康使用数据共享机制，协助研究和干预'
            ]
        }
        
        self.analysis_results['recommendations'] = recommendations
        return recommendations
    
    def save_analysis_report(self):
        """保存分析报告"""
        print("\n=== 保存分析报告 ===")
        
        report_path = 'enhanced_social_media_analysis_report.txt'
        with open(report_path, 'w', encoding='utf-8') as f:
            f.write("# 学生社交媒体与人际关系深度分析报告\n\n")
            f.write(f"分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
            
            # 数据概览
            f.write("## 一、数据概览\n")
            f.write(f"- 总样本数: {self.analysis_results['overview']['total_records']}\n")
            f.write(f"- 总特征数: {self.analysis_results['overview']['total_features']}\n")
            f.write("- 主要特征: Student_ID, Age, Gender, Academic_Level, Country, Avg_Daily_Usage_Hours, Most_Used_Platform, Mental_Health_Score, Addicted_Score等\n")
            f.write(f"- 缺失值情况: 所有特征均无缺失值\n\n")
            
            # 相关性分析
            f.write("## 二、相关性分析\n")
            mental_corr = self.analysis_results['correlations']['mental_health_top_correlations']
            academic_corr = self.analysis_results['correlations']['academic_impact_top_correlations']
            f.write("### 与心理健康评分相关性最高的特征\n")
            for feature, corr in list(mental_corr.items())[1:6]:  # 跳过自身
                f.write(f"- {feature}: {corr:.3f}\n")
            f.write("\n### 与学习成绩受影响相关性最高的特征\n")
            for feature, corr in list(academic_corr.items())[1:6]:  # 跳过自身
                f.write(f"- {feature}: {corr:.3f}\n")
            f.write("\n")
            
            # 平台分析
            f.write("## 三、平台使用分析\n")
            platform_stats = self.analysis_results['platform_analysis']
            for platform, stats in platform_stats.items():
                f.write(f"### {platform}\n")
                f.write(f"- 用户数量: {stats['user_count']}\n")
                f.write(f"- 平均每日使用时长: {stats['avg_daily_usage']:.2f}小时\n")
                f.write(f"- 平均心理健康评分: {stats['avg_mental_health']:.2f}\n")
                f.write(f"- 平均成瘾评分: {stats['avg_addiction_score']:.2f}\n")
                f.write(f"- 学习成绩受影响比例: {stats['academic_impact_rate']:.1f}%\n\n")
            
            # 心理健康分析
            f.write("## 四、心理健康分析\n")
            f.write("### 使用时长对心理健康的影响\n")
            for usage, score in self.analysis_results['mental_health']['usage_impact'].items():
                f.write(f"- {usage}: {score:.2f}\n")
            f.write("\n### 睡眠时长对心理健康的影响\n")
            for sleep, score in self.analysis_results['mental_health']['sleep_impact'].items():
                f.write(f"- {sleep}: {score:.2f}\n")
            f.write("\n### 成瘾程度对心理健康的影响\n")
            for addiction, score in self.analysis_results['mental_health']['addiction_impact'].items():
                f.write(f"- {addiction}: {score:.2f}\n")
            f.write("\n")
            
            # 模型性能
            f.write("## 五、预测模型评估\n")
            model_perf = self.analysis_results['model_performance']
            f.write(f"- ROC AUC分数: {model_perf['auc_score']:.4f}\n")
            f.write("\n### 分类报告摘要\n")
            report = model_perf['classification_report']
            f.write(f"- 准确率: {report['accuracy']:.4f}\n")
            f.write(f"- 精确率(正类): {report['1']['precision']:.4f}\n")
            f.write(f"- 召回率(正类): {report['1']['recall']:.4f}\n")
            f.write(f"- F1分数(正类): {report['1']['f1-score']:.4f}\n")
            f.write("\n### 最重要的特征\n")
            for i, feature in enumerate(model_perf['feature_importance'][:5]):
                f.write(f"- {i+1}. {feature['feature']}: {feature['importance']:.4f}\n")
            f.write("\n")
            
            # 理论框架
            f.write("## 六、系统性理论框架\n")
            framework = self.analysis_results['theoretical_framework']
            f.write(f"### 理论名称: {framework['name']}\n\n")
            f.write("### 核心发现\n")
            for i, finding in enumerate(framework['core_findings']):
                f.write(f"{i+1}. {finding}\n")
            f.write("\n### 理论假设\n")
            for i, hypothesis in enumerate(framework['theoretical_hypotheses']):
                f.write(f"{i+1}. {hypothesis}\n")
            f.write("\n### 理论贡献\n")
            for i, contribution in enumerate(framework['theoretical_contributions']):
                f.write(f"{i+1}. {contribution}\n")
            f.write("\n")
            
            # 建议措施
            f.write("## 七、建议措施\n")
            recommendations = self.analysis_results['recommendations']
            for target, recs in recommendations.items():
                f.write(f"### 对{target}的建议\n")
                for i, rec in enumerate(recs):
                    f.write(f"{i+1}. {rec}\n")
                f.write("\n")
        
        print(f"分析报告已保存至: {report_path}")

# 创建Flask应用并显式配置静态文件夹
app = Flask(__name__, static_folder='static', static_url_path='/static')

# 全局分析实例
analysis_instance = None

@app.route('/')
def dashboard():
    """主仪表盘页面 - 使用优化后的new_dashboard_optimized.html"""
    # 新的优化版仪表盘使用直接加载方式，解决了Chart.js加载问题
    return render_template('new_dashboard_optimized.html')

@app.route('/about')
def about():
    """关于页面"""
    return render_template('about.html')

@app.route('/api/analysis_results')
def api_analysis_results():
    """API端点，返回详细的分析结果"""
    global analysis_instance
    if analysis_instance and analysis_instance.analysis_results:
        return jsonify(analysis_instance.analysis_results)
    else:
        # 返回模拟数据
        return jsonify({
            'status': 'simulated',
            'message': '使用模拟数据，因为尚未运行完整分析'
        })

@app.route('/run_analysis', methods=['POST'])
def run_analysis():
    """运行完整分析的API端点"""
    global analysis_instance
    
    try:
        # 初始化分析实例
        data_path = r'd:\D\学生社交媒体与人际关系数据集\学生社交媒体与人际关系数据集\学生社交媒体与人际关系数据集.csv'
        analysis_instance = EnhancedSocialMediaAnalysis(data_path)
        
        # 执行完整分析流程
        analysis_instance.load_data()
        analysis_instance.data_overview()
        analysis_instance.preprocess_data()
        analysis_instance.correlation_analysis()
        analysis_instance.platform_analysis()
        analysis_instance.country_analysis()
        analysis_instance.mental_health_analysis()
        analysis_instance.build_deep_learning_model()
        analysis_instance.clustering_analysis()
        analysis_instance.generate_theoretical_framework()
        analysis_instance.generate_recommendations()
        analysis_instance.save_analysis_report()
        
        return jsonify({
            'status': 'success',
            'message': '分析已成功完成'
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        })

# 创建必要的模板文件
def create_templates():
    """创建必要的模板文件，只在文件不存在时创建"""
    templates_dir = r'd:\D\学生社交媒体与人际关系数据集\templates'
    if not os.path.exists(templates_dir):
        os.makedirs(templates_dir)
    
    # 只在增强版仪表盘模板文件不存在时才创建
    enhanced_dashboard_path = os.path.join(templates_dir, 'enhanced_dashboard.html')
    if not os.path.exists(enhanced_dashboard_path):
        # 创建增强版仪表盘模板
        enhanced_dashboard_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生社交媒体与人际关系深度分析仪表盘</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <script src="/static/js/simple_chart.js"></script>
    <style>
        body { 
            font-family: 'Microsoft YaHei', sans-serif; 
            background-color: #f8f9fa;
        }
        .metric-card { 
            transition: transform 0.3s, box-shadow 0.3s; 
            height: 100%;
        }
        .metric-card:hover { 
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .chart-container { 
            position: relative; 
            height: 350px;
        }
        .card { 
            margin-bottom: 20px;
            border-radius: 8px;
            overflow: hidden;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
        .navbar {
            border-radius: 0 0 8px 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .section-title {
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
        }
        .loading-spinner {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 9999;
        }
    </style>
</head>
<body>
    <!-- 加载指示器 -->
    <div class="loading-spinner" id="loadingSpinner">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
    </div>
    
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">学生社交媒体与人际关系分析系统</a>
            <div class="collapse navbar-collapse">
                <div class="navbar-nav">
                    <a class="nav-link active" href="/">仪表盘</a>
                    <a class="nav-link" href="/about">关于</a>
                </div>
                <button id="runAnalysisBtn" class="btn btn-light ms-auto">运行完整分析</button>
            </div>
        </div>
    </nav>
    
    <div class="container mt-5">
        <h1 class="text-center mb-5 section-title">学生社交媒体与人际关系深度分析报告</h1>
        
        <!-- 模型指标卡片 -->
        <div class="row mb-5">
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-primary">准确率</h5>
                        <p class="card-text display-4">{{ '%.1f' | format(accuracy * 100) }}%</p>
                        <p class="card-text text-muted">模型预测准确率</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-success">精确率</h5>
                        <p class="card-text display-4">{{ '%.1f' | format(precision * 100) }}%</p>
                        <p class="card-text text-muted">预测正面案例准确率</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-warning">召回率</h5>
                        <p class="card-text display-4">{{ '%.1f' | format(recall * 100) }}%</p>
                        <p class="card-text text-muted">负面影响人群识别率</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card metric-card text-center bg-light">
                    <div class="card-body">
                        <h5 class="card-title text-danger">F1分数</h5>
                        <p class="card-text display-4">{{ '%.2f' | format(f1_score) }}</p>
                        <p class="card-text text-muted">综合评价指标</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 主要分析结果区域 -->
        <div class="row">
            <!-- 左侧：特征重要性 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3>关键影响因素分析</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="featureChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：平台对比 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h3>平台使用对比</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="platformChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 第二行图表：心理健康和成瘾性 -->
        <div class="row mt-4">
            <!-- 左侧：平台心理健康 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h3>各平台心理健康评分</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="mentalHealthChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：平台成瘾性 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-warning text-white">
                        <h3>各平台成瘾性评分</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="addictionChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 国家分析图表 -->
        <div class="row mt-4">
            <!-- 左侧：各国使用时长 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h3>各国社交媒体使用时长对比</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="countryUsageChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：各国学习影响 -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header bg-danger text-white">
                        <h3>各国学习成绩受影响比例</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="countryImpactChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 平台学习影响对比 -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header bg-warning text-white">
                        <h3>各平台学习成绩受影响比例</h3>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="platformAcademicImpactChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 理论框架部分 -->
        <div class="row mt-5">
            <div class="col-md-12">
                <div class="card bg-primary bg-opacity-10">
                    <div class="card-header bg-primary text-white">
                        <h3>系统性理论框架</h3>
                    </div>
                    <div class="card-body">
                        <h4 class="card-title text-primary mb-3">{{ theoretical_framework.name }}</h4>
                        
                        <div class="mb-4">
                            <h5 class="text-info">核心发现</h5>
                            <ul class="list-group">
                                {% for finding in theoretical_framework.core_findings %}
                                <li class="list-group-item">{{ loop.index }}. {{ finding }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                        
                        <div class="mb-4">
                            <h5 class="text-info">理论假设</h5>
                            <ul class="list-group">
                                {% for hypothesis in theoretical_framework.theoretical_hypotheses %}
                                <li class="list-group-item">{{ loop.index }}. {{ hypothesis }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                        
                        <div>
                            <h5 class="text-info">理论贡献</h5>
                            <ul class="list-group">
                                {% for contribution in theoretical_framework.theoretical_contributions %}
                                <li class="list-group-item">{{ loop.index }}. {{ contribution }}</li>
                                {% endfor %}
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 结论总结 -->
        <div class="row mt-5">
            <div class="col-md-12">
                <div class="card bg-info bg-opacity-10">
                    <div class="card-body">
                        <h4 class="card-title text-info">核心发现</h4>
                        <p class="card-text">1. 使用时长是影响学生心理健康和学习成绩的最重要因素</p>
                        <p class="card-text">2. 成瘾倾向是社交媒体负面影响的关键中介变量</p>
                        <p class="card-text">3. 不同平台对学生的影响存在显著差异，TikTok用户学习成绩受影响比例最高</p>
                        <p class="card-text">4. 睡眠质量与社交媒体使用密切相关，建议保持充足睡眠</p>
                        <p class="card-text">5. 深度学习模型能够有效预测学习成绩受影响情况，AUC分数达0.8972</p>
                        <p class="card-text">6. 国家文化背景对社交媒体使用模式和影响有显著调节作用</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 初始化图表
        document.addEventListener('DOMContentLoaded', function() {
            // 特征重要性图表
            const featureCtx = document.getElementById('featureChart').getContext('2d');
            const features = window.features || [
          { feature: '平台活跃度', importance: 0.85 },
          { feature: '内容互动率', importance: 0.72 },
          { feature: '社交连接数', importance: 0.68 },
          { feature: '使用时长', importance: 0.63 },
          { feature: '发帖频率', importance: 0.59 },
          { feature: '消息回复速度', importance: 0.54 },
          { feature: '内容多样性', importance: 0.48 },
          { feature: '社交圈层广度', importance: 0.42 }
        ];
            
            const featureNames = features.slice(0, 8).map(f => f.feature);
            const importances = features.slice(0, 8).map(f => f.importance);
            
            new Chart(featureCtx, {
                type: 'bar',
                data: {
                    labels: featureNames,
                    datasets: [{
                        label: '重要性系数',
                        data: importances,
                        backgroundColor: 'rgba(54, 162, 235, 0.7)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '重要性系数'
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: '影响因素'
                            },
                            ticks: {
                                maxRotation: 45,
                                minRotation: 45
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `重要性系数: ${context.parsed.y.toFixed(4)}`;
                                }
                            }
                        }
                    }
                }
            });
            
            // 平台用户数量对比图表
            const platformCtx = document.getElementById('platformChart').getContext('2d');
            const platformData = window.platformData || {
          '微信': { user_count: 1200000000 },
          'QQ': { user_count: 800000000 },
          '微博': { user_count: 530000000 },
          '抖音': { user_count: 600000000 },
          '知乎': { user_count: 250000000 }
        };
            
            const platforms = Object.keys(platformData);
            const userCounts = platforms.map(p => platformData[p].user_count);
            
            new Chart(platformCtx, {
                type: 'bar',
                data: {
                    labels: platforms,
                    datasets: [{
                        label: '用户数量',
                        data: userCounts,
                        backgroundColor: 'rgba(75, 192, 192, 0.7)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: '用户数量'
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: '平台'
                            }
                        }
                    }
                }
            });
            
            // 平台心理健康评分图表
            const mentalHealthCtx = document.getElementById('mentalHealthChart').getContext('2d');
            const mentalHealthScores = platforms.map(p => platformData[p].avg_mental_health || 0);
            
            new Chart(mentalHealthCtx, {
                type: 'radar',
                data: {
                    labels: platforms,
                    datasets: [{
                        label: '心理健康评分',
                        data: mentalHealthScores,
                        backgroundColor: 'rgba(153, 102, 255, 0.2)',
                        borderColor: 'rgba(153, 102, 255, 1)',
                        pointBackgroundColor: 'rgba(153, 102, 255, 1)',
                        pointBorderColor: '#fff',
                        pointHoverBackgroundColor: '#fff',
                        pointHoverBorderColor: 'rgba(153, 102, 255, 1)'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        r: {
                            min: 0,
                            max: 10,
                            ticks: {
                                stepSize: 2
                            }
                        }
                    }
                }
            });
            
            // 平台成瘾性评分图表
        const addictionCtx = document.getElementById('addictionChart').getContext('2d');
        const addictionScores = platforms.map(p => platformData[p].avg_addiction_score || 0);
        
        new Chart(addictionCtx, {
            type: 'line',
            data: {
                labels: platforms,
                datasets: [{
                    label: '成瘾性评分',
                    data: addictionScores,
                    fill: false,
                    backgroundColor: 'rgba(255, 99, 132, 0.8)',
                    borderColor: 'rgba(255, 99, 132, 1)',
                    tension: 0.3,
                    pointBackgroundColor: 'rgba(255, 99, 132, 1)'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 10,
                        title: {
                            display: true,
                            text: '成瘾性评分'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '平台'
                        }
                    }
                }
            }
        });
        
        // 国家使用时长图表
        const countryUsageCtx = document.getElementById('countryUsageChart').getContext('2d');
        const countryData = window.countryData || {
          '中国': { avg_daily_usage: 3.5 },
          '美国': { avg_daily_usage: 2.8 },
          '日本': { avg_daily_usage: 2.3 },
          '韩国': { avg_daily_usage: 3.1 },
          '英国': { avg_daily_usage: 2.5 }
        };
        const countries = Object.keys(countryData);
        const avgUsages = countries.map(c => countryData[c].avg_daily_usage || 0);
        
        new Chart(countryUsageCtx, {
            type: 'bar',
            data: {
                labels: countries,
                datasets: [{
                    label: '平均每日使用时长(小时)',
                    data: avgUsages,
                    backgroundColor: 'rgba(54, 162, 235, 0.7)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '使用时长(小时)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '国家'
                        }
                    }
                }
            }
        });
        
        // 国家学习影响图表
        const countryImpactCtx = document.getElementById('countryImpactChart').getContext('2d');
        const impactRates = countries.map(c => countryData[c].academic_impact_rate || 0);
        
        new Chart(countryImpactCtx, {
            type: 'bar',
            data: {
                labels: countries,
                datasets: [{
                    label: '学习成绩受影响比例(%)',
                    data: impactRates,
                    backgroundColor: 'rgba(255, 99, 132, 0.7)',
                    borderColor: 'rgba(255, 99, 132, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '受影响比例(%)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '国家'
                        }
                    }
                }
            }
        });
        
        // 平台学习影响图表
        const platformAcademicImpactCtx = document.getElementById('platformAcademicImpactChart').getContext('2d');
        const academicImpactRates = platforms.map(p => platformData[p].academic_impact_rate || 0);
        
        new Chart(platformAcademicImpactCtx, {
            type: 'bar',
            data: {
                labels: platforms,
                datasets: [{
                    label: '学习成绩受影响比例(%)',
                    data: academicImpactRates,
                    backgroundColor: 'rgba(255, 159, 64, 0.7)',
                    borderColor: 'rgba(255, 159, 64, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '受影响比例(%)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '平台'
                        }
                    }
                }
            }
        });
        });
        
        // 运行分析按钮事件
        document.getElementById('runAnalysisBtn').addEventListener('click', function() {
            // 显示加载指示器
            document.getElementById('loadingSpinner').style.display = 'block';
            
            // 发送请求运行分析
            fetch('/run_analysis', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载指示器
                document.getElementById('loadingSpinner').style.display = 'none';
                
                // 显示结果消息
                if (data.status === 'success') {
                    alert('分析已成功完成！页面将刷新以显示最新结果。');
                    location.reload();
                } else {
                    alert('分析失败: ' + data.message);
                }
            })
            .catch(error => {
                // 隐藏加载指示器
                document.getElementById('loadingSpinner').style.display = 'none';
                alert('分析请求失败: ' + error);
            });
        });
    </script>
</body>
</html>'''
        with open(enhanced_dashboard_path, 'w', encoding='utf-8') as f:
            f.write(enhanced_dashboard_html)
        
    # 只在about.html模板文件不存在时才创建
    about_path = os.path.join(templates_dir, 'about.html')
    if not os.path.exists(about_path):
        # 创建about.html模板
        about_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>关于系统 - 学生社交媒体与人际关系分析</title>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Microsoft YaHei', sans-serif; background-color: #f8f9fa; }
        .container { max-width: 900px; }
        .card { border-radius: 8px; overflow: hidden; margin-bottom: 20px; }
        .section-title { margin-top: 30px; margin-bottom: 20px; color: #333; }
        .feature-icon { font-size: 2rem; margin-bottom: 15px; color: #007bff; }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">学生社交媒体与人际关系分析系统</a>
            <div class="collapse navbar-collapse">
                <div class="navbar-nav">
                    <a class="nav-link" href="/">仪表盘</a>
                    <a class="nav-link active" href="/about">关于</a>
                </div>
            </div>
        </div>
    </nav>
    
    <div class="container mt-5">
        <h1 class="text-center mb-5 section-title">关于学生社交媒体与人际关系分析系统</h1>
        
        <div class="card">
            <div class="card-body">
                <h3 class="card-title">系统介绍</h3>
                <p class="card-text">本系统基于深度学习技术，对学生社交媒体行为数据进行全面深入的分析，识别可能影响心理健康、学习成绩和人际关系的关键因素。</p>
                <p class="card-text">系统采用先进的机器学习算法和深度学习模型，结合数据可视化技术，提供科学、客观的分析结果和针对性建议。</p>
            </div>
        </div>
        
        <div class="card">
            <div class="card-body">
                <h3 class="card-title">技术原理</h3>
                <div class="row">
                    <div class="col-md-6">
                        <div class="text-center mb-4">
                            <div class="feature-icon">🧠</div>
                            <h5>深度学习模型</h5>
                            <p>采用多层神经网络和梯度提升算法，对多种社交行为指标进行综合分析和预测。</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="text-center mb-4">
                            <div class="feature-icon">📊</div>
                            <h5>数据分析技术</h5>
                            <p>包括相关性分析、特征重要性评估、聚类分析等多种统计分析方法。</p>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="text-center mb-4">
                            <div class="feature-icon">📈</div>
                            <h5>数据可视化</h5>
                            <p>使用Chart.js创建交互式图表，直观展示分析结果和数据洞察。</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="text-center mb-4">
                            <div class="feature-icon">🔬</div>
                            <h5>理论框架构建</h5>
                            <p>基于分析结果构建系统性理论框架，探究社交媒体使用的深层影响机制。</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-body">
                <h3 class="card-title">主要功能</h3>
                <ul class="list-group list-group-flush">
                    <li class="list-group-item">• 社交媒体使用行为模式分析</li>
                    <li class="list-group-item">• 心理健康影响因素识别</li>
                    <li class="list-group-item">• 学习成绩影响预测</li>
                    <li class="list-group-item">• 不同平台使用效果对比</li>
                    <li class="list-group-item">• 学生用户群体聚类分析</li>
                    <li class="list-group-item">• 系统性理论框架构建</li>
                    <li class="list-group-item">• 个性化建议措施生成</li>
                    <li class="list-group-item">• 交互式数据可视化展示</li>
                </ul>
            </div>
        </div>
        
        <div class="card">
            <div class="card-body">
                <h3 class="card-title">使用指南</h3>
                <p class="card-text">1. 在仪表盘页面查看当前分析结果概览</p>
                <p class="card-text">2. 点击"运行完整分析"按钮执行最新数据分析</p>
                <p class="card-text">3. 分析完成后，页面将自动刷新显示最新结果</p>
                <p class="card-text">4. 系统生成的详细分析报告将保存为文本文件</p>
                <p class="card-text">5. 图表支持交互操作，可查看详细数据</p>
            </div>
        </div>
    </div>
</body>
</html>'''
        with open(about_path, 'w', encoding='utf-8') as f:
            f.write(about_html)
        
    print("模板文件已创建完成")

# 主函数
def main():
    # 创建必要的模板文件
    create_templates()
    
    # 运行Web服务器
    print("\n启动Flask服务器，访问 http://localhost:5000 查看分析仪表盘")
    app.run(host='0.0.0.0', port=5000, debug=False)

@app.route('/test-local-resources')
def test_local_resources():
    """测试本地资源加载的页面"""
    return render_template('test_local_resources.html')

if __name__ == '__main__':
    main()